package com.jcark.ui.view.dropdown;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Point;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.jcark.ui.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Description: <br>
 *
 * @author King.Zi <br>
 * @date 2021/10/27 <br>
 * Email: 78688689@qq.com
 */
public class DropDownView extends LinearLayout {

    //顶部菜单布局
    private LinearLayout tabMenuView;
    //底部容器，包含popupMenuViews，maskView
    private FrameLayout containerView;
    private int containerViewChildIndex;
    //弹出菜单父布局
    private FrameLayout popupMenuViews;
    //遮罩半透明View，点击可关闭DropDownView
    private View maskView;
    //tabMenuView里面选中的tab位置，-1表示未选中
    private int current_tab_position = -1;

    //分割线颜色
    private int dividerColor = 0xffcccccc;
    //tab选中颜色
    private int textSelectedColor = 0xff890c85;
    //tab未选中颜色
    private int textUnselectedColor = 0xff111111;
    //遮罩颜色
    private int maskColor = 0x88888888;
    //tab字体大小
    private int menuTextSize = 14;
    //tab选中图标
    private int menuSelectedIcon;
    //tab未选中图标
    private int menuUnselectedIcon;
    //tab正选择值时
    private int menuSelectIcon;
    private float menuHeighPercent = 0.5f;
    private float menuWeight = 0.0f;
    private boolean hasUnderLine = false;
    private boolean hasDivider = false;
    //选择后是否保持高亮（即选中状态）
    private boolean isSelectedHighlight = false;
    private int menuWidth = ViewGroup.LayoutParams.WRAP_CONTENT;
    private int menuPaddingLeft;
    private int menuPaddingRight;
    private int menuPaddingTop;
    private int menuPaddingBottom;
    //菜单间距（指第2+个菜单距离前一个菜单的间距）
    private int menuSpace;
    private Context context;
    private List<String> defaultTabTextList = new ArrayList<>();
    private OnTabSwitchListener onTabSwitchListener;

    public DropDownView(Context context) {
        super(context, null);
        this.context = context;
    }

    public DropDownView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        this.context = context;
    }

    public DropDownView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        setOrientation(VERTICAL);
        //add DropDownView添加自定义属性
        int menuBackgroundColor = 0xffffffff;
        int underlineColor = 0xffcccccc;
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DropDownView);
        underlineColor = a.getColor(R.styleable.DropDownView_ddv_under_line_color, underlineColor);
        dividerColor = a.getColor(R.styleable.DropDownView_ddv_divider_color, dividerColor);
        textSelectedColor = a.getColor(R.styleable.DropDownView_ddv_text_selected_color,
                textSelectedColor);
        textUnselectedColor = a.getColor(R.styleable.DropDownView_ddv_text_unselected_color,
                textUnselectedColor);
        menuBackgroundColor = a.getColor(R.styleable.DropDownView_ddv_background_color,
                menuBackgroundColor);
        maskColor = a.getColor(R.styleable.DropDownView_ddv_mask_color, maskColor);
        menuTextSize = a.getDimensionPixelSize(R.styleable.DropDownView_ddv_text_size, menuTextSize);
        menuSelectedIcon = a.getResourceId(R.styleable.DropDownView_ddv_selected_icon, menuSelectedIcon);
        menuSelectIcon = a.getResourceId(R.styleable.DropDownView_ddv_select_icon, menuSelectIcon);
        menuUnselectedIcon = a.getResourceId(R.styleable.DropDownView_ddv_unselected_icon,
                menuUnselectedIcon);
        menuHeighPercent = a.getFloat(R.styleable.DropDownView_ddv_height_percent, menuHeighPercent);
        hasUnderLine = a.getBoolean(R.styleable.DropDownView_ddv_has_underline, true);
        menuWeight = a.getFloat(R.styleable.DropDownView_ddv_menu_weight, 0f);
        menuWidth = a.getDimensionPixelSize(R.styleable.DropDownView_ddv_menu_width, ViewGroup.LayoutParams.WRAP_CONTENT);
        menuPaddingLeft = a.getDimensionPixelSize(R.styleable.DropDownView_ddv_padding_left, 0);
        menuPaddingRight = a.getDimensionPixelSize(R.styleable.DropDownView_ddv_padding_right, 0);
        menuPaddingTop = a.getDimensionPixelSize(R.styleable.DropDownView_ddv_padding_top, 0);
        menuPaddingBottom = a.getDimensionPixelSize(R.styleable.DropDownView_ddv_padding_bottom, 0);
        menuSpace = a.getDimensionPixelSize(R.styleable.DropDownView_ddv_menu_space, 0);
        isSelectedHighlight = a.getBoolean(R.styleable.DropDownView_ddv_selected_highlight, false);
        a.recycle();

        //初始化tabMenuView并添加到tabMenuView
        tabMenuView = new LinearLayout(context);
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        tabMenuView.setPadding(menuPaddingLeft, menuPaddingTop, menuPaddingRight, menuPaddingBottom);
        tabMenuView.setOrientation(HORIZONTAL);
        tabMenuView.setLayoutParams(params);
        tabMenuView.setBackgroundColor(menuBackgroundColor);
        addView(tabMenuView, 0);

        //为tabMenuView添加下划线
        int index = 1;
        if (hasUnderLine) {
            View underLine = new View(getContext());
            underLine.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    dpToPx(1.0f)));
            underLine.setBackgroundColor(underlineColor);
            addView(underLine, index);
            underLine.setVisibility(INVISIBLE);
            index++;
        }
        //初始化containerView并将其添加到DropDownView
        containerView = new FrameLayout(context);
        containerView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
        containerView.setBackground(context.getResources().getDrawable(R.drawable.bg_drop_down_menu_integral));
        addView(containerView, index);
    }

    public DropDownView setContext(Context context) {
        this.context = context;
        return this;
    }

    /**
     * 初始化DropDownView
     *
     * @param tabTexts
     * @param popupViews
     * @param contentView
     */
    public void setDropDownView(@NonNull List<String> tabTexts, @NonNull List<View> popupViews,
                                @NonNull View contentView) {
        if (tabTexts.size() != popupViews.size()) {
            throw new IllegalArgumentException("params not match, tab list size should be equal" +
                    " popup views size");
        }

        containerViewChildIndex = 0;
        defaultTabTextList = tabTexts;
        for (int i = 0; i < tabTexts.size(); i++) {
            addTab(tabTexts, i);
        }
        //0
        if (containerView.getChildCount() > 0) {
            containerView.removeAllViews();
        }
        if (null != contentView) {
            ViewGroup contentViewParent = (ViewGroup) contentView.getParent();
            if (null != contentViewParent && contentViewParent.getChildCount() > 0) {
                contentViewParent.removeAllViews();
            }
        }
        containerView.addView(contentView, containerViewChildIndex);
        containerViewChildIndex++;

        maskView = new View(getContext());
        maskView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
        maskView.setBackgroundColor(maskColor);
        maskView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                closeView();
            }
        });
        //1
        containerView.addView(maskView, containerViewChildIndex);
        maskView.setVisibility(GONE);
        containerViewChildIndex++;

        if (containerView.getChildAt(containerViewChildIndex) != null) {
            containerView.removeViewAt(containerViewChildIndex);
        }

        //2
        popupMenuViews = new FrameLayout(getContext());
        popupMenuViews.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (getScreenSize(getContext()).y * menuHeighPercent)));
        popupMenuViews.setVisibility(GONE);
        containerView.addView(popupMenuViews, containerViewChildIndex);

        for (int i = 0; i < popupViews.size(); i++) {
            popupViews.get(i).setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            popupMenuViews.addView(popupViews.get(i), i);
        }
    }

    public void setDropDownView(@NonNull List<String> tabTexts, @NonNull List<View> popupViews,
                                @NonNull View contentView, View noDataView) {
        containerViewChildIndex = 0;
        if (noDataView != null) {
            if (containerView.getChildAt(0) != null) {
                containerView.removeViewAt(0);
            }
            containerView.addView(noDataView, 0);
            containerViewChildIndex++;
        }

        setDropDownView(tabTexts, popupViews, contentView);
    }

    public void setDropDownMenuVisible(boolean visible) {
        tabMenuView.setVisibility(visible ? VISIBLE : GONE);
    }

    public void setNoDataViewVisible(boolean visible) {
        if (containerView != null) {
            containerView.getChildAt(0).setVisibility(visible ? VISIBLE : GONE);
        }
    }

    private void addTab(@NonNull List<String> tabTexts, int i) {
        LinearLayout tabLayout = new LinearLayout(context);
        LayoutParams params = null;
        if (menuWeight > 0) {
            params = new LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, menuWeight);
        } else {
            params = new LayoutParams(menuWidth, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(0 != i && menuSpace > 0 ? menuSpace : menuPaddingLeft, 0, 0, 0);
        }
        tabLayout.setLayoutParams(params);
        tabLayout.setOrientation(HORIZONTAL);

        final TextView tab = new TextView(getContext());
        tab.setSingleLine();
        tab.setEllipsize(TextUtils.TruncateAt.END);
        tab.setGravity(Gravity.LEFT);
        tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, menuTextSize);
        tab.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        tab.setTextColor(textUnselectedColor);
        tab.setCompoundDrawablesWithIntrinsicBounds(null, null,
                getResources().getDrawable(menuUnselectedIcon), null);
        tab.setCompoundDrawablePadding(dpToPx(5));
        tab.setText(tabTexts.get(i));
        //tab.setTag(tabTexts.get(i));
        tab.setPadding(dpToPx(5), dpToPx(12), dpToPx(5), dpToPx(12));
        //添加点击事件
        tab.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != onTabSwitchListener) {
                    onTabSwitchListener.onTabSwitch(v);
                }
                switchView(tab);
            }
        });
        tabLayout.addView(tab);
        tabMenuView.addView(tabLayout);
        //添加分割线
        if (i < tabTexts.size() - 1) {
            View view = new View(getContext());
            view.setLayoutParams(new LayoutParams(dpToPx(0.5f),
                    ViewGroup.LayoutParams.MATCH_PARENT));
            view.setBackgroundColor(dividerColor);
            if (!hasDivider) {
                view.setVisibility(INVISIBLE);
            }
            tabMenuView.addView(view);
        }
    }

    /**
     * 改变tab文字
     *
     * @param text
     */
    public void setTabText(String text) {
        if (current_tab_position != -1) {
            getTextView(tabMenuView.getChildAt(current_tab_position)).setText(text);
            getTextView(tabMenuView.getChildAt(current_tab_position)).setTag(text);
        }
    }

    public void setTabClickable(boolean clickable) {
        for (int i = 0; i < tabMenuView.getChildCount(); i = i + 2) {
            getTextView(tabMenuView.getChildAt(i)).setClickable(clickable);
        }
    }

    public TextView getTextView(View view) {
        if (view instanceof LinearLayout) {
            LinearLayout layout = (LinearLayout) view;
            if (layout.getChildAt(0) instanceof TextView) {
                return (TextView) layout.getChildAt(0);
            }
        }
        return null;
    }

    /**
     * 关闭菜单
     */
    public void closeView() {
        if (current_tab_position != -1) {
            if (!isSelectedHighlight) {
                getTextView(tabMenuView.getChildAt(current_tab_position)).setTextColor(textUnselectedColor);
            }
            getTextView(tabMenuView.getChildAt(current_tab_position)).setCompoundDrawablesWithIntrinsicBounds(null, null,
                    getResources().getDrawable(menuSelectedIcon), null);
            popupMenuViews.setVisibility(View.GONE);
            popupMenuViews.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.dd_menu_out));
            maskView.setVisibility(GONE);
            maskView.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.dd_mask_out));
            current_tab_position = -1;
        }
    }

    /**
     * DropDownView是否处于可见状态
     *
     * @return
     */
    public boolean isShowing() {
        return current_tab_position != -1;
    }

    /**
     * 切换菜单
     *
     * @param target
     */
    private void switchView(View target) {
        TextView textView;
        for (int i = 0; i < tabMenuView.getChildCount(); i++) {
            if (tabMenuView.getChildAt(i) instanceof LinearLayout) {
                textView = ((TextView) ((LinearLayout) tabMenuView.getChildAt(i)).getChildAt(0));
            } else {
                continue;
            }
            if (target == textView) {
                if (current_tab_position == i) {
                    closeView();
                } else {
                    if (current_tab_position == -1) {
                        popupMenuViews.setVisibility(View.VISIBLE);
                        popupMenuViews.setAnimation(AnimationUtils.loadAnimation(getContext(),
                                R.anim.dd_menu_in));
                        maskView.setVisibility(VISIBLE);
                        maskView.setAnimation(AnimationUtils.loadAnimation(getContext(),
                                R.anim.dd_mask_in));
                        popupMenuViews.getChildAt(i / 2).setVisibility(View.VISIBLE);
                    } else {
                        popupMenuViews.getChildAt(i / 2).setVisibility(View.VISIBLE);
                    }
                    current_tab_position = i;
                    //((TextView) tabMenuView.getChildAt(i)).setTextColor(textSelectedColor);
                    textView.setTextColor(textSelectedColor);
                    if (null == textView.getTag()) {
                        textView.setTag(textView.getText());
                    }
                    /* KING：去掉右侧已选择图标*/
                    textView.setCompoundDrawablesWithIntrinsicBounds(null, null,
                            getResources().getDrawable(menuSelectIcon), null);
                }
            } else {
                //((TextView) tabMenuView.getChildAt(i)).setTextColor(textUnselectedColor);
                //textView.setTextColor(textUnselectedColor);
                //根据是否选中高亮以及是否第一次选择来设置颜色
                textView.setTextColor(isSelectedHighlight && null != textView.getTag() ? textSelectedColor : textUnselectedColor);
               /* if (isContainsText(String.valueOf(textView.getTag()))) {
                    textView.setTextColor(textUnselectedColor);
                } else {
                    textView.setTextColor(textSelectedColor);
                }*/

                textView.setCompoundDrawablesWithIntrinsicBounds(null, null,
                        getResources().getDrawable(menuSelectedIcon), null);
                popupMenuViews.getChildAt(i / 2).setVisibility(View.GONE);
            }
        }
    }

    public int dpToPx(float value) {
        float scale = getResources().getDisplayMetrics().density;
        return (int) (value * scale + 0.5f);
    }

    private boolean isContainsText(String tag) {
        if (TextUtils.isEmpty(tag)) {
            return false;
        }
        if (null != defaultTabTextList && defaultTabTextList.size() > 0) {
            for (int i = 0; i < defaultTabTextList.size(); i++) {
                if (defaultTabTextList.get(i).equalsIgnoreCase(tag)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 获取屏幕尺寸
     *
     * @param context
     * @return
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private Point getScreenSize(Context context) {
        WindowManager windowManager =
                (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) {
            return new Point(display.getWidth(), display.getHeight());
        } else {
            Point point = new Point();
            display.getSize(point);
            return point;
        }
    }

    public void setOnTabSwitchListener(OnTabSwitchListener listener) {
        this.onTabSwitchListener = listener;
    }

    public interface OnTabSwitchListener {
        void onTabSwitch(View v);
    }
}